package com.learning.security.service;

import com.learning.security.controller.vo.UserSaveReqVO;
import com.learning.security.dal.dataobject.AdminUserDO;
import com.learning.security.dal.mysql.AdminUserMapper;
import com.learning.security.dal.mysql.AdminUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private AdminUserRoleMapper adminUserRoleMapper;

    @Override
    public Long createUser(UserSaveReqVO userSaveReqVO) {
        AdminUserDO adminUserDO = new AdminUserDO();
        adminUserDO.setUsername(userSaveReqVO.getUsername());
        adminUserDO.setPassword(passwordEncoder.encode(userSaveReqVO.getPassword()));
        adminUserDO.setNickname(userSaveReqVO.getNickname());
        adminUserDO.setRemark(userSaveReqVO.getRemark());
        adminUserDO.setEmail(userSaveReqVO.getEmail());
        adminUserDO.setMobile(userSaveReqVO.getMobile());
        adminUserDO.setSex(userSaveReqVO.getSex());
        adminUserMapper.insert(adminUserDO);
        return adminUserDO.getId();
    }

    @Override
    public AdminUserDO getUserByUsername(String username) {
        return adminUserMapper.getUserByUsername(username);
    }

    @Override
    public boolean isPasswordMatch(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    @Override
    public AdminUserDO getUser(Long userId) {

        return adminUserMapper.selectById(userId);
    }

    @Override
    public boolean assignRole(Long userId, Long roleId) {
        return adminUserMapper.assignRole(userId, roleId);
    }
}
